package com.bnzj.cloud.business.core.web;

import java.util.List;
import java.util.Optional;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.bnzj.cloud.business.core.persistence.entity.SysResourceMeta;
import com.bnzj.cloud.business.core.service.SysResourceMetaService;
import com.bnzj.core.action.ActionType;
import com.bnzj.core.action.annotation.Action;
import com.bnzj.core.exception.BusinessException;
import com.bnzj.core.persistence.query.CompareExpression;
import com.bnzj.core.persistence.query.CompareType;
import com.bnzj.core.persistence.query.IExpression;
import com.bnzj.core.persistence.query.QueryHelpBean;
import com.bnzj.core.persistence.util.EntityUtils;
import com.bnzj.core.rest.CurrentUserService;
import com.bnzj.core.rest.ResponseResult;
import com.bnzj.core.rest.ResultCode;
import com.bnzj.core.rest.UserInfo;
import com.bnzj.core.util.BeanUtils;
import com.bnzj.core.webmvc.util.WebMvcUtils;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;

/**
 * @author Barry
 * @createDate 2020/3/27
 * @description
 */
@Tag(name = "资源菜单", description = "资源菜单")
@RestController
@RequestMapping("/system/resource/meta")
public class SysResourceMetaController {

    @Autowired
    private CurrentUserService currentUserService;

    @Autowired
    private SysResourceMetaService sysResourceMetaService;

    @Operation(summary = "分页查询", description = "",
            parameters = {@Parameter(in = ParameterIn.PATH, name = "keyWords", description = "根据名称", allowEmptyValue = true,
                    allowReserved = true, schema = @Schema(implementation = String.class, description = "根据名称"))})
    @GetMapping(value = "/page")
    public ResponseResult<Page<SysResourceMeta>> getSettingPage(HttpServletRequest request) {
        Pageable pageable = WebMvcUtils.initPage(request, Sort.by(Sort.Direction.DESC, "create_time"));
        QueryHelpBean bean = SysResourceMetaService.getQueryHelpBean();
        bean.setPageable(pageable);
        //资源名称模糊搜索
        IExpression orCondition1 = CompareExpression.build("name", CompareType.like, request.getParameter("keyWords"));
        bean.addWhere(orCondition1);
        Page<SysResourceMeta> all = sysResourceMetaService.findAll(bean);
        return ResponseResult.success(all);
    }


    @Operation(summary = "根据id查询")
    @GetMapping("/one/{id}")
    public ResponseResult<SysResourceMeta> getById(@Parameter(in = ParameterIn.PATH, name = "id", description = "主键", required = true) @PathVariable("id") Long id) {
        Optional<SysResourceMeta> optional = sysResourceMetaService.findById(id);
        return ResponseResult.success(optional.orElse(null));
    }


    @Operation(summary = "保存")
    @Action(descriprion = "后台资源保存",moduleName = "后台资源",operateType = ActionType.ADD_DATA)
    @PostMapping("save")
    public ResponseResult<?> addSetting(@RequestBody SysResourceMeta sysDictionary) {
        UserInfo userInfo = currentUserService.getUserInfo();
        EntityUtils.saveBefore(sysDictionary, userInfo.getAccount(), userInfo.getName());
        sysResourceMetaService.save(sysDictionary);
        return ResponseResult.success();
    }

    @Operation(summary = "更新")
    @Action(descriprion = "后台资源更新",moduleName = "后台资源",operateType = ActionType.UPDATE_DATA)
    @PostMapping("/update")
    public ResponseResult<?> updateSetting(@RequestBody SysResourceMeta sysSetting) {
        if (ObjectUtils.isEmpty(sysSetting.getId())) {
            throw new BusinessException(ResultCode.getResultCode(ResultCode.BAD_REQUEST));
        }
        UserInfo userInfo = currentUserService.getUserInfo();
        Optional<SysResourceMeta> sysSettingOpt = sysResourceMetaService.findById(sysSetting.getId());
        if (!sysSettingOpt.isPresent()) {
            throw new BusinessException(ResultCode.getResultCode(ResultCode.RESOURCE_NOT_EXIST));
        }
        SysResourceMeta sysSettingDb = sysSettingOpt.get();
        BeanUtils.copyProperties(sysSetting, sysSettingDb);
        EntityUtils.saveBefore(sysSettingDb, userInfo.getAccount(), userInfo.getName());
        sysResourceMetaService.save(sysSettingDb);
        return ResponseResult.success();
    }


    @Operation(summary = "获取所有后台资源列表", description = "获取所有后台资源列表")
    @RequestMapping(value = "/metas", method = RequestMethod.GET)
    public ResponseResult<List<SysResourceMeta>> getMetaList(SysResourceMeta meta) {
        List<SysResourceMeta> all = sysResourceMetaService.findAll(meta);
        return ResponseResult.success(all);
    }


    @Operation(summary = "根据按钮Id获取该按钮下所有资源", description = "根据按钮Id获取该按钮下所有资源")
    @GetMapping(value = "/meta/{resourceId}")
    public ResponseResult<List<SysResourceMeta>> getMetasByMenuId(@PathVariable("resourceId") Long resouceId) {
        List<SysResourceMeta> list = sysResourceMetaService.findByResourceId(resouceId);
        return ResponseResult.success(list);
    }


    /**
     * @depict
     * @参数
     * @返回值
     * @创建人 Barry
     * @创建时间 2019/9/2
     * @修改人和其它信息
     */
    @Operation(summary = "根据用户和菜单ID获取资源", description = "根据用户和菜单ID获取后台资源")
    @GetMapping(value = "/meta/curr-user/{resourceId}")
    public ResponseResult<List<SysResourceMeta>> findCurrentUserMetaByParentId(
            @Parameter(name = "resourceId", description = "资源上级菜单ID")
            @PathVariable(value = "resourceId", required = true) Long resourceId) {
        String userName = currentUserService.getAccount();
        return ResponseResult.success(sysResourceMetaService.findCurrentUserMetaByParentId(userName, resourceId));
    }

}
